<template>
    <view class="swiper-content">
        <view class="hander-top p-lr-32 w-s flex-j-sb--a-ct">
            <view class="icon-back-wrap" @click="onBack">
                <image class="icon-back" src="./images/icon-back.png" mode="widthFix" />
            </view>
            <view class="centerBox">
                <view v-if="isShowSwitch">
                    <xuan-switch :defaultSwitch="isShowOriginal" @change="changeSwitch" />
                </view>
                <view class="count">
                    {{currentTime}}
                </view>
                
            </view>
            
            <view class="count">{{currentImg + 1}} / {{ imgs.length }}</view>
        </view>
        <view class="photos">
            <view class="canvasBg" v-if='!isShowOriginal'>
                <canvas id="canvas" canvas-id="canvas" class="canvas" 
                   :style="{height:canvasH+'px',width:canvasW+'px'}"></canvas>
            </view>
        </view>

        <swiper class="swiper-img" :current="currentImg" :duration="300" @change="changeSwiper">
            <swiper-item class="swiper-item" v-for="(item, index) in imgs" :key="index">
                <view class="img-page">
                    <movable-area scale-area>
                        <!-- <movable-view style="display: flex;flex-direction: column;" > -->
                        <movable-view direction="all" scale="true" scale-min="1" scale-max="4" >
                            <!-- 存储在腾讯云上边的图片:src="item.photoAddress+'?imageMogr2/thumbnail/!50p'", 内存会减少一半-->
                            <image class="max-img" v-if="isShowOriginal" :lazy-load="true" mode="aspectFit"
                                :src="item.photoAddress" />
                                
                            <image class="max-img" v-if="!isShowOriginal&&imgList.length>0" mode="aspectFit"
                                :src="imgList[0].src" />
                           
                        </movable-view>
                    </movable-area>
                </view>
            </swiper-item>
        </swiper>
        <view class="imageContent" v-if='hasOver'>
            <u-loading-icon text="加载中" color='#67C23A' textColor='#67C23A' textSize="18"></u-loading-icon>
        </view>
        <view class="item-bottom">
            <view :class="isHistoryShow?'item-bottom-left-history':'item-bottom-left'" @click="openPopup">
                历史对比
            </view>
            <scroll-view class="scroll-view_H " :scroll-x="true" :scroll-into-view="scrollTopIndex"
                :scroll-with-animation="true" scroll-left="20" v-if="isSwiperShow">
                <view class="img-page-box scroll-view-item_H" :class="currentImg == index ? 'img-page-checked' : ''"
                    v-for="(item, index) in imgs" :key="index" :id="`scrollToIndex${index}`" @click.stop="toImg(index)">
                    <image class="img" :src="item.thumbnail" mode="aspectFill" />
                </view>
            </scroll-view>
            <view :class="isSwiperShow?'item-bottom-right-history': 'item-bottom-right'"
                @click="isSwiperShow=!isSwiperShow">《</view>
        </view>
        <view>
            <u-popup :show="isPopupShow" :round="10" mode="center" :closeOnClickOverlay='false' closeable @close="closePopup">
                <view class='detailBox'>
                    <view class="title">选择要对比的历史</view>
                    <u--form labelPosition="left" :model="compareForm" ref="uForm" labelWidth='80'>

                        <u-form-item label="光照类型" @click="showFaceLight= true" prop="faceLight" borderBottom>
                            <u--input placeholder="请选择光照类型" v-model="compareForm.faceLight" border="none"></u--input>
                            <u-icon slot="right" name="arrow-right"></u-icon>

                        </u-form-item>
                        <u-form-item label="脸部部位" @click="showFacePart= true" prop="facePart" borderBottom>
                            <u--input placeholder="请选择光照类型" v-model="compareForm.facePart" border="none"></u--input>
                            <u-icon slot="right" name="arrow-right"></u-icon>
                        </u-form-item>
                        <u-form-item label="拍照设备" @click="showType= true" prop="type" borderBottom>
                        	   <u--input placeholder="请选择光照类型" v-model="compareForm.type" border="none"></u--input>
                           	<u-icon slot="right" name="arrow-right"></u-icon>

                        </u-form-item>
                        <button class='formLoginBtn' @click="formSearch">查询</button>
                        <u-picker :show="showFaceLight" :columns="columnsFaceLight" keyName="name"
                            @confirm="confirmFaceLight" @cancel="showFaceLight = false"></u-picker>
                        <u-picker :show="showFacePart" :columns="columnsFacePart" keyName="name"
                            @confirm="confirmFacePart" @cancel="showFacePart = false"></u-picker>
                        <u-picker :show="showType" :columns="columnsType" keyName="name" @confirm="confirmType"
                            @cancel="showType = false"></u-picker>

                    </u--form>
                </view>
            </u-popup>
            <u-button>打开</u-button>
        </view>

        <!--  <view class="handle-wrap flex-j-sb--a-ct p-lr-32">
      
      <view class="w-64 h-64"
            @click="isScale = !isScale">
        <image v-show="isScale"
               class="w-64 h-64"
               src="./images/icon-scale-yes.png"
               mode="widthFix" />
        <image v-show="!isScale"
               class="w-64 h-64"
               src="./images/icon-scale.png"
               mode="widthFix" />
      </view>

      <view class="w-64 h-64"
            @click="isCollect = !isCollect">
        <image v-show="isCollect"
               class="w-64 h-64"
               src="./images/icon-collect-yes.png"
               mode="widthFix" />
        <image v-show="!isCollect"
               class="w-64 h-64"
               src="./images/icon-collect.png"
               mode="widthFix" />
      </view>

      <view class="w-64 h-64"
            @click="isLike = !isLike">
        <image v-show="isLike"
               class="w-64 h-64"
               src="./images/icon-like-yes.png"
               mode="widthFix" />
        <image v-show="!isLike"
               class="w-64 h-64"
               src="./images/icon-like.png"
               mode="widthFix" />
      </view>

      <image class="w-64 h-64"
             src="./images/icon-set-wallpaper.png"
             mode="widthFix" />
      <image class="w-64 h-64"
             src="./images/icon-share.png"
             mode="widthFix" />
      <image class="w-64 h-64"
             src="./images/icon-download.png"
             mode="widthFix" />
    </view> -->

        <view class="pop" v-if="isPop">
            <view class="item" @click.stop="share()">分享图片</view>
            <!-- #ifndef H5 -->
            <view class="item" @click.stop="saveImg(false)">保存图片</view>
            <view class="item" @click.stop="saveImg(true)">保存全部图片</view>
            <!-- #endif -->
        </view>
    </view>
</template>

<script>
    import xuanSwitch from '@/components/xuan-switch/xuan-switch.vue'
    import {
        LoginApi
    } from '@/api/login-api.js'
    import {
        personalApi
    } from '@/api/patients/personal.js'
    export default {
        props: {
            newDataList: {
                type: Array,
                default: []
            },
            currentIndex: {
                type: Number,
                default: 0
            },
            patientId: {
                default: ''
            }

        },
        components: {
            xuanSwitch
        },
        data() {
            return {
                // imgs: [
                //   "https://pic2.zhimg.com/80/v2-6bc06520079e780ac1c550729f5cfa8d_1440w.webp",
                //   "https://img.tukuppt.com/photo-big/00/02/23/6188eaff33ec07243.jpg",
                //   "https://img0.baidu.com/it/u=4231555811,1903718579&fm=253&app=138&size=w931",
                //   "https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0509%2F1e1bac6cj00rbkpwf001ec000hs00q8c.jpg&thumbnail=660x2147483647&quality=80&type=jpg",
                //   "https://pic2.zhimg.com/80/v2-6bc06520079e780ac1c550729f5cfa8d_1440w.webp",
                //   "https://img.tukuppt.com/photo-big/00/02/23/6188eaff33ec07243.jpg",
                //   "https://img0.baidu.com/it/u=4231555811,1903718579&fm=253&app=138&size=w931",
                //   "https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0509%2F1e1bac6cj00rbkpwf001ec000hs00q8c.jpg&thumbnail=660x2147483647&quality=80&type=jpg",
                // ],
                imgs: [],
                currentImg: 0,
                currentTime:'',
                isPop: false,
                scrollTopIndex: "",
                isScale: false,
                isCollect: false,
                isLike: false,
                isShowOriginal: true,
                isShowSwitch: false,
                imgList: [],
                widthEle: 0, // 设备宽度
                heightEle: 0,
                canvasH: 0, //canvas高度
                canvasW: 0, //canvas宽度
                hasOver: false,
                percent: 0,
                timer: null,
                isHistoryShow: false,
                isPopupShow: false,
                isSwiperShow: true,
                pictureForm: {
                    pageNum: 1,
                    pageSize: 9999,
                    faceLight: '',
                    facePart: '',
                    type: '',
                    patientId: ''
                },
                compareForm: {
                    faceLight: '',
                    facePart: '',
                    type: '',
                },
                photo_lighting_type: [],
                sys_face_part: [],
                photo_upload_type: [],
                showFaceLight: false,
                columnsFaceLight: [],
                showFacePart: false,
                columnsFacePart: [],
                showType: false,
                columnsType: [],
                compareNum:1,

            };
        },
        mounted() {
            this.currentImg = this.currentIndex
            this.imgs = this.newDataList
            let signalObj = this.imgs.find((item, index) => {
                return index === this.currentImg
            })
            this.currentTime=signalObj.createTime
            if (signalObj.points) {
                this.isShowSwitch = true
            } else {
                this.isShowSwitch = false
            }
            this.getDictList('photo_lighting_type')
            this.getDictList('sys_face_part')
            this.getDictList('photo_upload_type')
        },
        methods: {
            /** id转化成对应的文字 */
            matchDict: function(key, id) {
                let _this = this;
                const result = _this[key];
                let textValue = "";
                result.forEach((item) => {
                    if (item.dictValue == id) {
                        textValue = item.dictLabel;
                    }
                });
                return textValue;
            },
            async getDictList(mType) {
                const res = await LoginApi.getDict(mType)
                res.data.forEach(item => {
                    item.name = item.dictLabel
                })
                this[mType] = res.data
            },
            async formSearch() {
                await this.getPhotoList()
                this.isPopupShow=false
            },
            
            confirmFaceLight(e) {
                this.compareForm.faceLight = e.value[0].name
                this.pictureForm.faceLight = e.value[0].dictValue
                this.showFaceLight = false
            },
            confirmFacePart(e) {
                this.compareForm.facePart = e.value[0].name
                this.pictureForm.facePart = e.value[0].dictValue
                this.showFacePart = false
            },
            confirmType(e) {
                this.compareForm.type = e.value[0].name
                this.pictureForm.type = e.value[0].dictValue
                this.showType = false
            },

            openPopup() {
                if(this.isHistoryShow){
                    this.imgs=this.newDataList
                    this.currentImg=this.currentIndex
                    let signalObj = this.imgs.find((item, index) => {
                        return index === this.currentImg
                    })
                    this.currentTime=signalObj.createTime
                    this.isHistoryShow=false
                }else{
                    this.isHistoryShow=true
                    this.isPopupShow = true
                    this.columnsFaceLight = []
                    this.columnsFacePart = []
                    this.columnsType = []
                    this.pictureForm= {
                        pageNum: 1,
                        pageSize: 9999,
                        faceLight: '',
                        facePart: '',
                        type: '',
                        patientId: ''
                    }
                    this.compareForm= {
                        faceLight: '',
                        facePart: '',
                        type: '',
                    }
                    this.columnsFaceLight.push(this.photo_lighting_type)
                    this.columnsFacePart.push(this.sys_face_part)
                    this.columnsType.push(this.photo_upload_type)
                    this.pictureForm.patientId = this.patientId
                }
                
            },
            closePopup() {
                this.isPopupShow = false
            },
            changeSwiper(e) {
                this.currentImg = e.detail.current;
                this.isShowOriginal = true
                let signalObj = this.imgs.find((item, index) => {
                    return index === this.currentImg
                })
                this.currentTime=signalObj.createTime
                if (signalObj.points) {
                    this.isShowSwitch = true
                } else {
                    this.isShowSwitch = false
                }

                this.scrollTopIndex = `scrollToIndex${e.detail.current}`;
            },
            changeSwitch(value) {
                this.isShowOriginal = value
                if (this.isShowOriginal) {
                    this.hasOver = false
                } else {
                    this.drawImgSingle()
                }
            },
            toImg(index) {
                this.currentImg = index;
                let signalObj = this.imgs.find((item, index) => {
                    return index === this.currentImg
                })
                this.currentTime=signalObj.createTime
            },
            onBack() {
                // uni.navigateBack();
                this.$emit('closePreview')
            },
            //根据病人id获取图片列表
            getPhotoList() {
                personalApi.listPhotos(this.pictureForm).then((res) => {
                    if (res.rows.length > 0) {
                        this.imgs = res.rows;
                        this.currentImg=0
                        let signalObj = this.imgs.find((item, index) => {
                            return index === this.currentImg
                        })
                        this.currentTime=signalObj.createTime
                        this.imgs.forEach((it) => {
                            if (it.score && JSON.parse(it.score).left) {
                                it.scoreAi = 0.3 * JSON.parse(it.score).left.area * JSON.parse(it.score)
                                    .left.color
                            }
                            if (it.score && JSON.parse(it.score).brow) {
                                it.scoreAi = 0.3 * JSON.parse(it.score).brow.area * JSON.parse(it.score)
                                    .brow.color + 0.1 * JSON.parse(it.score).chin.area * JSON.parse(it
                                        .score).chin.color
                            }
                            if (it.score && JSON.parse(it.score).right) {
                                it.scoreAi = 0.3 * JSON.parse(it.score).right.area * JSON.parse(it
                                    .score).right.color
                            }
                            it.points = this.formatPoints(it.points)
            
                        })
                    } else {
                        this.imgs = [];
                    }
                });
            },
            //格式化画图组件点位格式数据
            formatPoints(data) {
                if (data != null) {
                    let mData = []
                    // console.log(JSON.parse(data))
                    JSON.parse(data).forEach((item, index) => {
                        let itPoint = []
                        item.forEach((it, mindex) => {
                            itPoint.push({
                                x: it[0],
                                y: it[1]
                            })
                            if (item.length - 1 === mindex) {
                                //最后一个点连接到第一个点形成闭合
                                itPoint.push({
                                    x: item[0][0],
                                    y: item[0][1]
                                })
                            }
                        })
                        mData.push({
                            points: itPoint,
                            type: 'route'
                        })
                    })
                    // console.log('mData', mData)
                    return mData
                } else {
                    return null
                }
            },
            
            async drawImgSingle() {
                let _this = this
                let arr = []
                _this.originalUrl = []
                _this.hasOver = true

                uni.getSystemInfo({
                    success: function(res1) {
                        _this.widthEle = res1.windowWidth //可使用窗口宽度
                        _this.heightEle = res1.windowHeight //可使用窗口高度
                        _this.imgList = []

                        let signalObj = _this.imgs.find((item, index) => {
                            return index == _this.currentImg
                        })
                        // console.log('signalObj--', signalObj)
                        uni.getImageInfo({
                            src: signalObj.photoAddress,
                            success: res => {
                                arr.push({
                                    src: res.path,
                                    index: _this.currentImg
                                })
                                // console.log('getImageInfo---', res)

                                // let el = 'canvas' + _this.currentImg
                                // console.log('el---', el)
                                let context = uni.createCanvasContext('canvas')
                                _this.canvasH = res.height
                                _this.canvasW = res.width
                                context.width = res.width
                                context.height = res.height
                                context.drawImage(res.path, 0, 0, res.width, res.height);
                                context.setStrokeStyle("#ff0000")
                                context.setLineWidth(3)
                                if (!signalObj.points) {
                                    signalObj.points = []
                                }
                                console.log('signalObj---', signalObj)
                                signalObj.points.forEach((t) => {
                                    t.points.forEach((m, n) => {
                                        if (n == 0) {
                                            context.moveTo(m.x,
                                                m.y)
                                        } else {
                                            context.lineTo(m.x,
                                                m.y)
                                        }
                                    })
                                    context.closePath();
                                })
                                context.stroke()
                                context.draw(true, () => { // 把以上内容画到 canvas 中
                                    setTimeout(() => {
                                        uni.canvasToTempFilePath({
                                            x: 0,
                                            y: 0,
                                            width: _this.canvasW,
                                            height: _this.canvasH,
                                            destWidth: _this
                                                .canvasW,
                                            destHeight: _this
                                                .canvasH,
                                            canvasId: 'canvas',
                                            success(res2) {

                                                _this.imgList.push({
                                                    index: _this
                                                        .currentImg,
                                                    src: res2
                                                        .tempFilePath
                                                })
                                                _this.hasOver =
                                                    false
                                                console.log('res2-------_this.imgList----',res2,_this.imgList)


                                            }
                                        })

                                    }, 500)

                                })

                            },
                        })
                    }
                })

            },
            //   share() {
            //     uni.downloadFile({
            //       // 下面一行时拼接预览PDF的地址！！！
            //       url: this.imgs[this.currentImg],
            //       success: function (res) {
            //         var filePath = res.tempFilePath;
            //         if (!filePath) return;
            //         uni.openDocument({
            //           filePath: filePath,
            //           success: function (res) {
            //             console.log(res);
            //             console.log("打开文档成功");
            //           },
            //         });
            //       },
            //     });
            //   },
            //   saveImg(isAll = false) {
            //     const that = this;
            //     if (!isAll) {
            //       uni.downloadFile({
            //         url: this.imgs[this.currentImg],
            //         success: (res) => {
            //           if (res.statusCode === 200) {
            //             uni.saveImageToPhotosAlbum({
            //               filePath: res.tempFilePath,
            //               success: function () {
            //                 uni.showToast({
            //                   icon: "none",
            //                   title: "保存成功",
            //                 });
            //                 that.isPop = false;
            //               },
            //               fail: function () {},
            //             });
            //           } else {
            //           }
            //         },
            //       });
            //       return;
            //     }
            //     this.imgs.forEach((item) => {
            //       uni.downloadFile({
            //         url: item,
            //         success: (res) => {
            //           if (res.statusCode === 200) {
            //             uni.saveImageToPhotosAlbum({
            //               filePath: res.tempFilePath,
            //               success: function () {
            //                 uni.showToast({
            //                   icon: "none",
            //                   title: "保存全部成功",
            //                 });
            //                 that.isPop = false;
            //               },
            //               fail: function () {},
            //             });
            //           } else {
            //           }
            //         },
            //       });
            //     });
            //   },

        },
    };
</script>

<style lang="scss" scoped>
    .swiper-content {
        width: 100%;
        height: 100vh;
        position: relative;
    }

    movable-view {
        display: flex;
        align-items: center;
        justify-content: center;

        width: 100%;
        height: 100%;
    }

    movable-area {
        position: fixed;

        overflow: hidden;

        width: 100%;
        height: 100%;

        transform: scale();
    }

    movable-view image {
        width: 100%;
    }

    uni-image>img {
        z-index: -1 !important;
    }

    .hander-top {
        position: absolute;
        z-index: 1000;
        top: 48rpx;
        left: 0;
        display: flex;
        justify-content: space-between;
        width: 100%;
        padding: 0 32rpx;
        box-sizing: border-box;

        .icon-back-wrap {
            width: 64rpx;
            height: 64rpx;

            .icon-back {
                width: 64rpx;
                height: 64rpx;
            }
        }
        .centerBox{
            display: flex;
            flex-direction: column; 
            align-items: center;
        }

        .count {
            height: 64rpx;
            line-height: 64rpx;
            box-sizing: border-box;
            padding: 0rpx 24rpx;
            color: #fff;
            border-radius: 24rpx;
            background: rgba(0, 0, 0, .4);
            font-size: 28rpx;
        }
    }

    .swiper-img {
        width: 100vw;
        height: 100vh;

        background-color: #000;

        .swiper-item {
            width: 100vw;
            height: 100vh;

            .img-page {
                display: flex;
                align-items: center;
                width: 100vw;
                height: 100vh;

                .max-img {
                    width: 100%;
                    height: 100%;
                }
            }
        }
    }

    .handle-wrap {
        position: absolute;
        z-index: 100;
        bottom: 40rpx;
        left: 0;

        width: 100%;
        display: flex;
        justify-content: space-between;
        padding: 32rpx;
        box-sizing: border-box;

        image {
            width: 64rpx;
            height: 64rpx;
        }

        width: 100%;
    }

    .item-bottom {
        position: fixed;
        z-index: 9999;
        // bottom: 110rpx;
        bottom: 0rpx;
        left: 0rpx;
        display: flex;
        // flex-direction: column;
        justify-content: space-between;
        width: 100vw;
        height: 260rpx;
        padding: 30rpx;

        transition: ease-in-out .3s;

        .item-bottom-left {
            margin-top: 30rpx;
            width: 60rpx;
            height: 130rpx;
            line-height: 60rpx;
            color: white;
            background-color: #2d3039;
            border-radius: 30rpx;
            text-align: center;
            writing-mode: vertical-rl;
        }

        .item-bottom-left-history {
            margin-top: 30rpx;
            width: 60rpx;
            height: 130rpx;
            line-height: 60rpx;
            color: white;
            background: #8951db;
            border-radius: 30rpx;
            text-align: center;
            writing-mode: vertical-rl;
        }

        .item-bottom-right {
            margin-top: 30rpx;
            width: 60rpx;
            height: 130rpx;
            line-height: 130rpx;
            color: white;
            background-color: #2d3039;
            border-radius: 30rpx;
            text-indent: 10rpx;
        }

        .item-bottom-right-history {
            margin-top: 30rpx;
            width: 60rpx;
            height: 130rpx;
            line-height: 130rpx;
            color: white;
            background-color: #2d3039;
            border-radius: 30rpx;
            text-indent: 10rpx;
            transform: rotate(180deg);
        }
    }

    ::v-deep .u-popup__content {
        // width: 85%;
        // min-height: 600rpx;
        // width: 600rpx;
        font-size: 28rpx;
        padding: 040rpx;

        .detailBox {
            .title {
                text-align: center;
                font-size: 38rpx;
                font-weight: bold;
            }

            .formLoginBtn {
                font-size: 28rpx;
                background: #2796f2;
                color: #fff;
                width: 200rpx;
                height: 60rpx;
                line-height: 60rpx;
                border-radius: 10rpx;
                font-weight: bold;
                margin: 40rpx auto 0 auto;
            }


        }
    }

    .small-list-page {
        min-height: 60rpx;
    }

    .scroll-Y {
        height: 300rpx;
    }

    .scroll-view_H {
        width: 80%;
        box-sizing: border-box;
        // padding-right: 32rpx;
        white-space: nowrap;
    }

    .scroll-view-item_H {
        display: inline-block;

        margin-right: 10rpx;

        transition: ease-in .1s;
        transform: scale(.8);

        border-radius: 11rpx;
        background: #c2c2c2;

        &:last-child {
            margin-right: 0;
        }

        .img {
            display: block;
            width: 110rpx;
            height: 180rpx;
        }
    }

    .img-page-checked {
        transform: translateY(-28rpx) scale(1);
    }

    .pop {
        position: fixed;
        z-index: 999999;
        top: 50%;
        left: 50%;

        overflow: hidden;

        width: 500rpx;

        transform: translate(-50%, -50%);

        border-radius: 20rpx;
        background-color: #fff;

        .item {
            height: 100rpx;
            padding: 0 50rpx;

            transition: all .2s;

            border-radius: 20rpx;

            line-height: 100rpx;

            &:active {
                background-color: #eee;
            }
        }
    }

    .photos {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: -1000%;
        opacity: 0;
        background-color: red;

        .canvasBg {
            position: absolute;
            width: 750rpx;
            // .canvas{
            //  position: absolute;
            // 	width:  750rpx;
            // }
        }
    }

    .imageContent {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);




    }
</style>
